package trackListGenerator;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public abstract class ImgurUploader {

    private static final String UPLOAD_URL = "https://api.imgur.com/3/image";

    public static String upload(File file) {
        InputStream imageIn = null;
        HttpURLConnection conn = null;
        InputStream responseIn = null;

        try {
            imageIn = new FileInputStream(file);

            conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
            conn.setDoOutput(true);

            conn.setRequestProperty("Authorization", "Client-ID 8a05c8b972acba3");
            try (OutputStream out = conn.getOutputStream()) {
                copy(imageIn, out);
                out.flush();
            }

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                responseIn = conn.getInputStream();
                return onInput(responseIn);
            } else {
                System.out.println("Error: " + conn.getResponseMessage());
                return null;
            }
        } catch (Exception ex) {
            return null;
        } finally {
            try {
                responseIn.close();
                conn.disconnect();
                imageIn.close();
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }

    private static int copy(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[8192];
        int count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    private static String onInput(InputStream in) throws Exception {
        StringBuilder sb = new StringBuilder();
        Scanner scanner = new Scanner(in);
        while (scanner.hasNext()) {
            sb.append(scanner.next());
        }
        return sb.toString();
    }

}
